<?php
class Order_model extends CI_Model {

	function __construct()
    {
        parent::__construct();
    }
    /**
	 * 获取点卡信息
	 * @param int $id
	 */
	public function find_by_id($id) {
		$this->db->where('id', $id);
		return $this->db->get('orders')->row_array();
	}
	
	public function add($data) {
		$this->db->insert("orders", $data);
		return $this->db->insert_id();
	}
	
	public function find_orders($user_id) {
		$sql = " select *as total from orders  where created_by=" . intval($user_id);
		return $this->db->query($sql)->row_array();
	}
	
	public function find_cards_by_order($order_id) {
		$sql = " select card_id from card_order  where order_id =" . intval($order_id);
		return $this->db->query($sql)->result_array();
	}
	
	public function add_card_to_order($card_id, $order_id) {
		$data = array('card_id' => $card_id, 'order_id' => $order_id );
		$this->db->insert("card_order", $data);
	}
	
	public function set_as_afforded($order_id, $pay_method='cash') {
		$sql = " update orders  set atatus = 1, pay_time= " . $this->db->escape(date("Y-m-d H:i:s")). ", pay_method=" . 
		$this->db->escape($pay_method) .
		 "  where id=" . intval($order_id);
		return $this->db->query($sql);
	}
	
	public function update_trade_no($order_id, $trade_no) {
		$sql = " update orders  set trade_no='" . $trade_no . "', status=1,pay_time='" .date("Y-m-d H:i:s") . "' where id=" . intval($order_id);
		return $this->db->query($sql);
	}
	
	public function get_count_by_condition($condition) {
		$sql = "select count(*) as total from orders o where o.status=1";
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
	public function find_by_condition($condition, $offset = 0, $limit = 20) {
		$sql = "select o.*,count(co.card_id) as card_count,u.nickname from orders o
		left join card_order co on co.order_id=o.id 
		left join users u on u.id=o.created_by
		where o.status=1 group by o.id limit " . $offset . "," . $limit;
		return $this->db->query($sql)->result_array();
	}
}